package com.corx.network.mysqlstorage.util;


import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 使用示例：
 * // 生成当日表名（格式：prefix_deviceId_yyyymmdd）
 * System.out.println(generateStructuredTableName(deviceId, TimeGranularity.DAILY));
 * <p>
 * // 生成指定日期月级表名（格式：prefix_deviceId_yyyymm）
 * LocalDate customDate = LocalDate.of(2023, 12, 25);
 * System.out.println(generateStructuredTableName(deviceId, TimeGranularity.MONTHLY, customDate));
 *
 * </p>
 *
 * @author gx
 * @version 1.0.0
 */
public class TableNameGeneratorUtil {

    /**
     * 分隔符
     */
    private static final String DELIMITER = "_";

    /**
     * 设备数据表名称
     */
    private static final String DEVICE_DATA_STRUCTURED = "corx_device_data_structured";

    public enum TimeGranularity {
        /**
         * 不添加时间
         */
        NONE,
        /**
         * 按天分表
         */
        DAILY,
        /**
         * 按月分表
         */
        MONTHLY,
        /**
         * 按年分表
         */
        YEARLY
    }

    /**
     * 默认使用当前日期
     */
    public static String generateStructuredTableName(String deviceId, TimeGranularity granularity) {
        return generateStructuredTableName(deviceId, granularity, LocalDate.now());
    }

    /**
     * 支持自定义日期
     */
    public static String generateStructuredTableName(String deviceId, TimeGranularity granularity, LocalDate date) {
        if (TimeGranularity.NONE == granularity) {
            return DEVICE_DATA_STRUCTURED + DELIMITER + deviceId;
        }
        String dateSuffix = formatDate(date, granularity);
        return String.join(DELIMITER,
            DEVICE_DATA_STRUCTURED,
            deviceId,
            dateSuffix
        );
    }

    private static String formatDate(LocalDate date, TimeGranularity granularity) {
        DateTimeFormatter formatter;
        switch (granularity) {
            case YEARLY:
                formatter = DateTimeFormatter.ofPattern("yyyy");
                break;
            case MONTHLY:
                formatter = DateTimeFormatter.ofPattern("yyyyMM");
                break;
            case DAILY:
                formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                break;
            default:
                throw new IllegalArgumentException("Unsupported time granularity");
        }
        return date.format(formatter);
    }

}
